/*=============================================================================
#    The element-comm is a tentative program used to test our ideas.           
#                       Copyright (C)  bgao                                    
#
#     This program is free software; you can redistribute it and/or            
#      modify it under the terms of the GNU General Public License             
#     as published by the Free Software Foundation; either version 2           
#         of the License, or (at your option) any later version.               
#
#     This program is distributed in the hope that it will be useful,          
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            
#             GNU General Public License for more details.                    
#
#    You should have received a copy of the GNU General Public License        
#     along with this program; if not, write to the Free Software             
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,             
#                       MA  02110-1301, USA.                                  
#==============================================================================
# $Id$ 
#
# $Author$ 
#
# $Revision$ 
#
# $Date$ 
#
# Description: 
#
=============================================================================*/
#include 	<avr/io.h>
#include    "rtos-wsn.h"
#include	"led.h"
#include 	"cc2420.h"
#include	"wsn-platform.h"

extern unsigned long wsn_systime;

void adc_init(void)
{
	/*I/O init*/
	DDRF &= ~BIT_SET(ADC_IN);/*ADC*/
	DDRE |= BIT_SET(LIGHT_EN);/*Light sensor*/

	/*ADC register */
	/*single ended input ADC1,Left Adjust Result*/
	ADMUX = BIT_SET(MUX0)|BIT_SET(ADLAR);
	/*Once Running mode, fclk=CLKadc/128=8M/128=62.5khz, 208us*/
	ADCSRA = BIT_SET(ADEN) | BIT_SET(ADFR) | BIT_SET(ADPS2) | BIT_SET(ADPS1) | BIT_SET(ADPS0);
}


static void adc_light_start(void)
{
	wsn_EnterCritical();
	/* power on light sensor */
	PORTE |=BIT_SET(LIGHT_EN);
	/* start once conversion */
	ADCSRA |= BIT_SET(ADSC);
	wsn_LeaveCritical();
}
/*
static void adc_temp_start(void)
{
	wsn_EnterCritical();
	DDRE |= _BV(PE6);
	PORTE |=_BV(PE6);
	ADCSRA |= _BV(ADSC);
	wsn_LeaveCritical();
}*/

uint16 adc_data_10bits(void)
{
	/* ADLAR ==1 */
	uint16 sensor_data;
	sensor_data = (ADCL>>6);
	sensor_data += (ADCH<<2);
	return sensor_data;
}

uint8 adc_data_8bits(void)
{
	/* ADLAR ==1 */
	return ADCH;
}


void adc_light_task(void)
{
	uint16 data;
	uint8 adc_int_flag = 0;
	
	adc_light_start();
	while(adc_int_flag == 0)
		adc_int_flag = (ADCSRA & 0x10);	
	data = adc_data_10bits();
	led_toggle(LED_YELLOW);
	/** Sensor data is %d,systime MSB:%d **/
	WSN_debug(0x8045,2,data,wsn_systime >> 16);
}


